package com.movieproject.src;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Map;

import com.movieproject.daos.UserDAO;
import com.movieproject.dataobjects.User;

//import org.jboss.logging.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/register")
public class RegisterController {

	@RequestMapping(method = RequestMethod.GET)

	public String viewRegistration(Map<String, Object> model) {
		User userForm = new User();    
		model.put("userForm", userForm);


		return "Registration";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processRegistration(@ModelAttribute("userForm") User user,
			Map<String, Object> model) {

		ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");

		UserDAO userDAO = (UserDAO) context.getBean("userDAO");

		String fName = user.getFirstName();
		String lName = user.getLastName();
		String email = user.getEmail();
		String address = user.getAddress();
		String city = user.getCity();
		String state = user.getState();
		String zip = user.getZip();
		String userName = user.getUsername();
		String pword = user.getPassword();
		String accessLvl = "1";

		//use the security class to create a hash of the username and password
		//Implemented by Josh M. 6/18/14
		String userHash = "";
		String passHash = "";
		
		try {
			userHash = AppSecurity.createHash(userName);
			passHash = AppSecurity.createHash(pword);
			
			System.out.println(userHash);
			System.out.println(passHash);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		}
		
		User customer = new User(fName, lName, address, city, state, zip, email, accessLvl, userHash, passHash);
		userDAO.insert(customer);
		

		return "RegistrationSuccess";
	}
}